import { OrderStatus } from '../config';
import { OrderLists, CancelOrder, ConfirmPay, ConfirmReceipt, OrderFile } from '../../../services/order/order';
import util from '../../../utils/util';

Page({
  page: { size: 5, num: 1, },

  data: {
    tabs: [
      { key: '', text: '全部' },
      { key: OrderStatus.PENDING_DELIVERY, text: '待发货', info: '' },
      { key: OrderStatus.PENDING_RECEIPT, text: '待收货', info: '' },
      { key: OrderStatus.PENDING_PAYMENT, text: '待支付', info: '' },
      { key: OrderStatus.COMPLETE, text: '已完成', info: '' },
    ],
    OrderStatus,
    curTab: '',
    orderList: [],
    listLoading: 0,   // 加载
    pullDownRefreshing: false,
    emptyImg: 'https://file.ydc360.com/common/ygzc/empty-order.png',
    backRefresh: false,
    status: '',
    fileVisible: false,   // 订单附件
    fileList: [],
  },

  onLoad(query) {
    let status = parseInt(query.status);
    status = this.data.tabs.map((t) => t.key).includes(status) ? status : '';
    this.init(status);
    this.pullDownRefresh = this.selectComponent('#wr-pull-down-refresh');
  },

  onShow() {
    if (!this.data.backRefresh) return;
    this.onRefresh();
    this.setData({ backRefresh: false });
  },

  onReachBottom() {
    if (this.data.listLoading === 0) {
      this.getOrderList(this.data.curTab);
    }
  },

  onPageScroll(e) {
    this.pullDownRefresh && this.pullDownRefresh.onPageScroll(e);
  },

  onPullDownRefresh_() {
    this.setData({ pullDownRefreshing: true });
    this.refreshList(this.data.curTab).then(() => {
      this.setData({ pullDownRefreshing: false });
      // callback();
    }).catch((err) => {
      this.setData({ pullDownRefreshing: false });
      Promise.reject(err);
    });
  },

  init(status) {
    status = status !== undefined ? status : this.data.curTab;
    this.setData({ status, });
    this.refreshList(status);
  },

  /* 订单列表 */
  getOrderList(state = '', reset = false) {
    const params = {
      page: { size: this.page.size, current: this.page.num, },
      state
    };
    this.setData({ listLoading: 1 });
    return OrderLists(params).then(res => {
      if (res.code == '0000') {
        this.page.num++;
        let orderList = res.data;
        return new Promise((resolve) => {
          if (reset) this.setData({ orderList: [] }, () => resolve());
          else resolve();
        }).then(() => {
          this.setData({
            orderList: this.data.orderList.concat(orderList),
            listLoading: orderList.length > 0 ? 0 : 2,
          });
        });
      }
    }).catch((err) => {
      this.setData({ listLoading: 3 });
      return Promise.reject(err);
    });
  },

  /* 订单按钮操作 */
  onOrderBtnTap(event) {
    let { order, type } = event.target.dataset, that = this;
    switch (type) {
      case 'takeDelivery':
        wx.showModal({
          title: "",
          content: "是否确认收货",
          showCancel: true,
          success: function (cif) {
            if (cif.confirm) {
              ConfirmReceipt({ orderId: order.id }).then(res => {
                if (res.code === '0000') {
                  util.showToast('操作成功');
                  that.refreshList(that.data.curTab)
                  that.init(OrderStatus.PENDING_PAYMENT)
                }
              })
            }
          }
        });
        break;
      case 'payment':
        wx.showModal({
          title: "",
          content: "是否确认支付",
          showCancel: true,
          success: function (cif) {
            if (cif.confirm) {
              ConfirmPay({ orderId: order.id }).then(res => {
                if (res.code === '0000') {
                  util.showToast('操作成功');
                  that.refreshList(that.data.curTab)
                }
              })
            }
          }
        });
        break;
      case 'logistics':
        wx.navigateTo({
          url: `/pages/order/delivery-detail/index?orderId=${order.id}`,
        });
        break;
      case 'invoice':
        OrderFile({ orderId: order.id, type: 1 }).then(res => {
          if (res.code === '0000') {
            let fileList = [];
            if (res.data) {
              res.data.fileList.forEach(item => {
                let type = util.getFileType(item)
                fileList.push({ type, url: item, iconName: `file-${type}` })
              });
              that.setData({ fileVisible: true, fileList })
            } else {
              util.showToast('文件未上传,请稍后再查看', 'none');
            }
          }
        })
        break;
      case 'cancel':
        wx.showModal({
          title: "",
          content: "是否确认取消订单",
          showCancel: true,
          success: function (cif) {
            if (cif.confirm) {
              CancelOrder({ orderId: order.id }).then(res => {
                if (res.code === '0000') {
                  util.showToast('操作成功');
                  that.refreshList(that.data.curTab)
                }
              })
            }
          }
        });
        break;
      default:
        break;
    }
  },

  /* 加载 */
  onReTryLoad() {
    this.getOrderList(this.data.curTab);
  },

  /* 监听Tab切换 */
  onTabChange(e) {
    const { value } = e.detail;
    this.setData({ status: value, });
    this.refreshList(value);
  },
  getOrdersCount() {
    return fetchOrdersCount().then((res) => {
      const tabsCount = res.data || [];
      const { tabs } = this.data;
      tabs.forEach((tab) => {
        const tabCount = tabsCount.find((c) => c.tabType === tab.key);
        if (tabCount) {
          tab.info = tabCount.orderNum;
        }
      });
      this.setData({ tabs });
    });
  },

  refreshList(status = '') {
    this.page = {
      size: this.page.size,
      num: 1,
    };
    this.setData({ curTab: status, orderList: [] });
    return Promise.all([
      this.getOrderList(status, true),
    ]);
  },

  onRefresh() {
    this.refreshList(this.data.curTab);
  },
  /* 订单详情 */
  OrderDetail(e) {
    const { order } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/order/order-detail/index?orderId=${order.id}`,
    });
  },
  /* 关闭文件附件 */
  ClosefileVisible() {
    this.setData({ fileVisible: false })
  },
});
